package cn.zjh.org.controller;

import cn.zjh.basic.util.PageList;
import cn.zjh.basic.util.AjaxResult;
import cn.zjh.org.domain.Department;
import cn.zjh.org.query.DepartmentQuery;
import cn.zjh.org.service.IDepartmentService;
import cn.zjh.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门接口类
 */
@Api(value = "部门接口类",description = "部门crud的相关操作")
@RestController
@RequestMapping("/department")
public class DepartmentController {
    //service注入
    @Autowired
    private IDepartmentService departmentService;
    //查找单个内容
    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个")
    public Department findOne(@PathVariable("id") Long id){
       return departmentService.findOne(id);
    }
    //查询所有
    @GetMapping
    @ApiOperation(value = "查询所有")
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    //删除
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    //添加或者修改
    @PutMapping
    @ApiOperation(value = "添加或者修改")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if(department.getId() == null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();

            return new AjaxResult(false,"操作成功");
        }
    }

    //分页查询
    @PostMapping
    @ApiOperation(value = "分页查询")
    @PreAuthorize(name = "部门列表",value = "department:list") //value后面用来做权限校验
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
       return departmentService.queryPage(departmentQuery);
    }


    //批量删除
    @PatchMapping
    @ApiOperation(value = "批量删除")
    @PreAuthorize(name = "部门删除",value = "department:delete") //value后面用来做权限校验
    public AjaxResult patchDel(@RequestBody List<Long> ids){
        try {
            departmentService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"批量删除失败");
        }
    }

    @GetMapping("/peatTree")
    @ApiOperation(value = "部门树")
    public List<Department> peatTree(){
        return departmentService.peatTree();
    }

}
